package org.itboys.core.service.mysql.web;

import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.core.common.SundayCommonConstants;
import org.itboys.core.dao.order.SundayAddProductOrderMapper;
import org.itboys.core.dao.order.SundayAddProductOrderSKUMapper;
import org.itboys.core.entity.mongo.SundayStore;
import org.itboys.core.entity.mysql.*;
import org.itboys.core.service.mongo.web.SundayStoreService;
import org.itboys.core.util.NumberUtil;
import org.itboys.mysql.service.BaseMySqlService;
import org.itboys.param.PageResult;
import org.itboys.param.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Author：贾琦磊
 * @Date：2018/8/17
 * @Description：进货单service
 */
@Service
public class SundayAddProductOrderService extends BaseMySqlService<SundayAddProductOrder>{
    /**
     * 单据编号前缀
     */
    private static final String ORDER_PREFIX="AP";


    @Autowired
    private SundayAddProductOrderMapper addProductOrderMapper;
    @Autowired
    private SundaySkuPriceService sundaySkuPriceService;
    @Autowired
    private SundayAddProductOrderSKUMapper addProductOrderSKUMapper;
    @Autowired
    private SundayStoreService storeService;
    @Autowired
    private SundaySkuService skuService;
    @Autowired
    private SundayProductService productService;
    @Autowired
    private SundayInStoreOrderService inStoreOrderService;

    public PageResult<SundayAddProductOrder> select(HttpServletRequest request){
        Map<String, Object> param = ParamUtil.packageMysqlPageParam(request,"number");
        param.put("isDeleted", SundayCommonConstants.NO);
        PageResult<SundayAddProductOrder> result = super.selectPage(param);
        List<SundayAddProductOrder> orders=result.getData();
        List<Long> storeIds=new ArrayList<>();
        for (SundayAddProductOrder order:orders
             ) {
            storeIds.add(order.getPreStoreId());
            storeIds.add(order.getCenterStoreId());
        }
        param.clear();
        param.put("isDeleted",SundayCommonConstants.NO);
        param.put("id in", storeIds);
        List<SundayStore> stores = storeService.list(param);
        //组装仓库信息
        for (SundayAddProductOrder order:orders
             ) {
            for (SundayStore store:stores
                 ) {
                if(order.getCenterStoreId().equals(store.getId())){
                    order.setCenterStoreName(store.getName());
                }
                if(order.getPreStoreId().equals(store.getId())){
                    order.setPreStoreName(store.getName());
                }
            }
        }
            result.setData(orders);
        return result;
    }


    @Transactional(rollbackFor = Exception.class)
    public void save(Long id, Long preStoreId, Long centerStoreId,String remark, List<SundayAddProductOrderSKU> skus){
        Long orderId;
        if(LongUtil.isNotZreo(id)){
            orderId=id;
            SundayAddProductOrder addProductOrder=new SundayAddProductOrder(id, remark,  preStoreId, centerStoreId);
            addProductOrderMapper.update(addProductOrder);
        }else{
            //新增单据自动生成编号
            String number = NumberUtil.generateNumber(ORDER_PREFIX);
            SundayAddProductOrder addProductOrder=new SundayAddProductOrder(id,number,1, remark,  preStoreId, centerStoreId);
            addProductOrderMapper.insert(addProductOrder);
            orderId=addProductOrder.getId();
        }
        //封装skus附属orderId
        for (SundayAddProductOrderSKU sku:skus
             ) {
            sku.setOrderId(orderId);
        }
        //更新全部skuOrder
        addProductOrderSKUMapper.deleteByOrderId(orderId);
        addProductOrderSKUMapper.insertSKUs(skus);
    }

    public SundayAddProductOrder findOne(Long id){
        if(!LongUtil.isNotZreo(id)){
            return null;
        }
        SundayAddProductOrder order = addProductOrderMapper.find(id);
        List<Long> ids=new ArrayList<>();
        ids.add(order.getCenterStoreId());
        ids.add(order.getPreStoreId());
        Map<String,Object> param=new HashMap();
        param.put("isDeleted",SundayCommonConstants.NO);
        param.put("id in",ids);
        List<SundayStore> stores = storeService.list(param);
        for (SundayStore store:stores
             ) {
            if(order.getCenterStoreId().equals(store.getId())){
                order.setCenterStoreName(store.getName());
            }
            if(order.getPreStoreId().equals(store.getId())){
                order.setPreStoreName(store.getName());
            }
        }
        param.clear();
        param.put("isDeleted",SundayCommonConstants.NO);
        param.put("orderId",order.getId());
        List<SundayAddProductOrderSKU> skuOrders = addProductOrderSKUMapper.select(param);
        ids.clear();
        for (SundayAddProductOrderSKU skuOrder:skuOrders
             ) {
            ids.add(skuOrder.getSKUId());
        }
        param.clear();
        param.put("isDeleted",SundayCommonConstants.NO);
        param.put("ids",ids);
        List<SundaySku> skus = skuService.select(param);
        ids.clear();
        for (SundaySku sku:skus
             ) {
            ids.add(sku.getProductId());
        }
        param.clear();
        param.put("isDeleted",SundayCommonConstants.NO);
        param.put("ids",ids);
        List<SundayProduct> products = productService.select(param);
       for (SundayAddProductOrderSKU skuOrder:skuOrders) {
            for (SundaySku sku:skus
                 ) {
                if(skuOrder.getSKUId().equals(sku.getId())){
                    for (SundayProduct product :products) {
                        if(product.getId().equals(sku.getProductId())){
                            skuOrder.setProductName(product.getName()+"("+sku.getNumber()+")");
                            break;
                        }
                    }
                    break;
                }
            }
        }
        order.setSkus(skuOrders);
        return order;
    }
    @Transactional(rollbackFor = Exception.class)
    public void setState(Long addProductOrderId,Integer state){
        SundayAddProductOrder order =new SundayAddProductOrder();
        order.setId(addProductOrderId);
        order.setState(state);
        //收货通过生成入库单
        if(SundayAddProductOrder.ORDER_STATE_THROUGH.equals(state)){
            //设置审核时间
            order.setApprovalTime(new Date());
        }
        if(SundayAddProductOrder.ORDER_STATE_RECEIVE.equals(state)){
            order.setReceiveTime(new Date());
            //根据补货单封装入库单以及入库单附表skus
            SundayAddProductOrder addProductOrder = super.find(addProductOrderId);
            SundayInStoreOrder inStoreOrder=new SundayInStoreOrder(
                    addProductOrder.getPreStoreId(),
                    addProductOrder.getCenterStoreId(),
                    SundayInStoreOrder.TYPE_ADD_PRODUCT,
                    addProductOrder.getRemark());
            Map<String,Object> param=new HashMap<>();
            param.put("isDeleted",SundayCommonConstants.NO);
            param.put("orderId",addProductOrderId);
            List<SundayAddProductOrderSKU> addProductOrderSKUS = addProductOrderSKUMapper.select(param);
            List<SundayInStoreOrderSKU> inStoreOrderSKUS=new ArrayList<>();
            for (SundayAddProductOrderSKU addProductOrderSKU:addProductOrderSKUS
                 ) {
                SundayInStoreOrderSKU inStoreOrderSKU=new SundayInStoreOrderSKU(
                        addProductOrderSKU.getSKUId()
                        ,addProductOrderSKU.getNum()
                );
                inStoreOrderSKUS.add(inStoreOrderSKU);
            }
            inStoreOrderService.save(inStoreOrder,inStoreOrderSKUS);
        }
        addProductOrderMapper.update(order);
    }
}
